package main

import (
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

// 数据库配置
type Databaseconf struct {
	User         string
	Password     string
	DatabaseName string
	Host         string
	Port         string
}

// 连接mysql
func ConnectMysql(conf *Databaseconf) error {
	sqlStr := fmt.Sprintf(`%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=true&loc=Local`, conf.User, conf.Password, conf.Host, conf.Port, conf.DatabaseName)
	db, err := gorm.Open(mysql.Open(sqlStr), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),

		//DisableForeignKeyConstraintWhenMigrating: true, // 禁止创建外键

		NamingStrategy: schema.NamingStrategy{ // 给创建表时候使用的

			SingularTable: true,
			// 全部的表名前面加前缀
			//TablePrefix: "mall_",
		},
	})

	if err != nil {
		return fmt.Errorf("数据库连接错误: %v", err)
	}

	GormDb = db
	return nil
}

// 同步数据库字段
func dbMigrate(db *gorm.DB) error {
	err := db.AutoMigrate(
		&Student{},
		&Teacher{},
		&Dormitory{},
		&Relation{},
	)
	return err
}
